package framework.jackson.custom;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 在不修改对象映射关系的情况下，使用 Mixin 临时调整序列化格式
 */
public class MixinTest {

    public static void main(String[] args) throws Exception {
        Obj.InnerObj innerObj = new Obj.InnerObj("value_g", "value_h");
        Obj obj = new Obj("value_a", innerObj, "value_c");

        // {"a":"value_a","b":{"h":"value_h"},"c":"value_c"}
        ObjectMapper mapper = new ObjectMapper();
        mapper.addMixIn(Obj.InnerObj.class, InnerObjMixIn.class);
        System.out.println(mapper.writeValueAsString(obj));

        String str = "{\"a\":\"value_a\",\"b\":{\"g\":\"value-g\",\"h\":\"value_h\"},\"c\":\"value_c\"}";
        ObjectMapper mapper2 = new ObjectMapper();
        mapper2.addMixIn(Obj.InnerObj.class, InnerObjMixIn2.class);
        System.out.println(mapper2.writeValueAsString(obj));
        Obj obj2 = mapper2.readValue(str, Obj.class);
        System.out.println(obj2);
    }

    /** 混合接口 */
    interface InnerObjMixIn {
        @JsonIgnore
        String getG();
    }

    /** 混合接口 */
    abstract class InnerObjMixIn2 {
        @JsonIgnore
        String g;
    }
}
